package com.example.planetexploder.module.firstpage;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.planetexploder.module.bookshelf.View_Fragment;
import com.example.planetexploder.module.edittext.View_EditText;
import com.example.planetexploder.adapter.MyAdapter_ItemInfo;
import com.example.planetexploder.bean.maindata.BookInfo;
import com.example.planetexploder.bean.maindata.ItemInfo;
import com.example.planetexploder.constants.SortConst;
import com.example.planetexploder.R;
import com.example.planetexploder.module.menu.View_Menu;
import com.example.planetexploder.module.picture.View_ImgDisplay;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;

/**
 * 主页面UI设计、菜单显示且监听功能、页面跳转和创建功能
 * @author lxx
 * 2019.10.19
 */

public class View_FirstPage extends AppCompatActivity implements AdapterView.OnItemLongClickListener {

    private Presenter_FirstPage presenter;
    private BookInfo firstBookInfo;
    private int sortTag;

    ArrayList<ItemInfo> mListMain;
    private GridView mGridView;
    private MyAdapter_ItemInfo mAdapter;
    private boolean isShowDelete = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        presenter = new Presenter_FirstPage(View_FirstPage.this);
        firstBookInfo = new BookInfo();

        try {
            firstBookInfo = presenter.get_FirstPageBookInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }

        sortTag = presenter.pSort.get_SortWay();//获取当前排序
        if(firstBookInfo.bookId != null) {
            mListMain = presenter.pBook.get_BookTable(firstBookInfo.bookId, sortTag);//初始化首页数据
        }
        else
        {
            mListMain = new ArrayList<ItemInfo>();
            Toast.makeText(View_FirstPage.this,"新建你的摘抄",Toast.LENGTH_LONG);
        }

        /**
         * 功能：绑定公共类MyGridViewAdapter，实现长按事件的监听并初始化数组
         * 修改日期：2019.10.19
         */
        mGridView = findViewById(R.id.gridViewMain);
        mGridView.setOnItemLongClickListener(this);//长按事件监听
        mAdapter = new MyAdapter_ItemInfo(View_FirstPage.this, mListMain);
        mGridView.setAdapter(mAdapter);

        /**
         * 底部的跳转功能实现
         * 2019.10.19
         */
        ImageView imageView_book = findViewById(R.id.shelf_unchosed);
        imageView_book.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(View_FirstPage.this, View_Fragment.class);
                startActivity(intent);
            }
        });

        /**
         * 功能：监控首页右下角加号(+)号按钮的单击行为，调用自定义函数来显示创建窗口
         * 修改日期：2019.10.19
         */
        final FloatingActionButton buttonPlusMain = findViewById(R.id.buttonPlusMain);
        buttonPlusMain.setOnClickListener(new View.OnClickListener() {
            @Override//监听Plus按钮
            public void onClick(View view) {
                plusButtonFirstPage(View_FirstPage.this).show();
            }
        });

        /**
         * 功能：设置GridView中item为单击事件，并根据单击效果进入编辑模式
         * 修改日期：2019.10.19
         */
        GridView gridView = findViewById(R.id.gridViewMain);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if(mListMain.get(position).isText()) {//跳转到文本编辑界面方法
                    transmitTextInfo(mListMain.get(position));
                }
                else{
                    transmitImageInfo(mListMain.get(position));
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshGridView();
    }

    /**
     * 功能：实现对显示页面中的长按删除功能，长按获取位置position，删除信息
     * 修改日期：2019.10.19
     */
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
        if (isShowDelete) {
            isShowDelete = false;
        } else {
            isShowDelete = true;
            mAdapter.setIsShowDelete(isShowDelete);
            mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                    presenter.pBook.delete_Item(firstBookInfo, mListMain.get(position).itemId);
                    deleteGridViewItems(position);//删除选中项
                    refreshGridView();//刷新ArrayList数组并重新绑定容器
                }

            });
        }
        mAdapter.setIsShowDelete(isShowDelete);//setIsShowDelete()方法用于传递isShowDelete值
        return true;
    }

    /**
     * 功能：删除选中项方法
     * 修改日期：2019.10.19
     */
    private void deleteGridViewItems(int position) {
        ArrayList<ItemInfo> newList = new ArrayList<ItemInfo>();
        if (isShowDelete) {
            mListMain.remove(position);
            isShowDelete = false;
        }
        newList.addAll(mListMain);
        mListMain.clear();
        mListMain.addAll(newList);

        //重新将items设置为单击事件，实现绑定
        GridView gridView = findViewById(R.id.gridViewMain);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                if(mListMain.get(position).isText()) {//跳转到文本编辑界面方法
                    transmitTextInfo(mListMain.get(position));
                }
                else{
                    transmitImageInfo(mListMain.get(position));
                }
            }
        });
    }

    /**
     * 功能：重写onCreateOptionMenu()方法来添加一个选项菜单
     * 修改日期：2019.10.19
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = new MenuInflater(this);
        menuInflater.inflate(R.menu.menu_main,menu);
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 功能：重写onOptionsItemSelected()方法，指定各个菜单被选择时，做出相应处理
     * 修改日期：2019.10.19
     */
   @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.Edit_Main:
                Intent intent = new Intent(View_FirstPage.this, View_Menu.class);
                startActivity(intent);
                break;

            case R.id.Updata_Main:
                presenter.pSort.set_SortWay(SortConst.ORDER_BY_MOD);
                sortTag = presenter.pSort.get_SortWay();
                refreshGridView();
                break;

            case R.id.CreateDown_Main:
                presenter.pSort.set_SortWay(SortConst.ORDER_BY_CRE_DOWN);
                sortTag = presenter.pSort.get_SortWay();
                refreshGridView();
                break;

            case R.id.CreateUp_Main:
                presenter.pSort.set_SortWay(SortConst.ORDER_BY_CRE_UP);
                sortTag = presenter.pSort.get_SortWay();
                refreshGridView();
                break;
                default:break;
        }
        return super.onOptionsItemSelected(item);
    }
    /**
     * 功能：单击加号跳出选项菜单
     * 修改日期：2019.10.19
     */
    public AlertDialog plusButtonFirstPage(final Context context) {
        final ItemInfo transInfo = new ItemInfo();//新建一个ItemInfo类并传递
        AlertDialog builder = new AlertDialog.Builder(context).setView(null)
        .setPositiveButton("新建文本集", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                transmitTextInfo(transInfo);
            }
        }).setNegativeButton("新建图片集", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        transmitImageInfo(transInfo);
                    }
                }).show();

        //居中显示按钮
        Button btnPositive = builder.getButton(AlertDialog.BUTTON_POSITIVE);
        Button btnNegative = builder.getButton(AlertDialog.BUTTON_NEGATIVE);
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) btnPositive.getLayoutParams();
        layoutParams.weight = 10;
        btnPositive.setLayoutParams(layoutParams);
        btnNegative.setLayoutParams(layoutParams);
        return builder;
    }

    /**
     * 功能：刷新ArrayList数组并重新绑定容器
     * 修改日期：2019.10.21
     */
    public void refreshGridView() {
        mListMain = presenter.pBook.get_BookTable(firstBookInfo.bookId,sortTag);
        mAdapter = new MyAdapter_ItemInfo(View_FirstPage.this, mListMain);//重新绑定一次adapter
        mGridView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();//刷新GridView
    }

    /**
     *功能：获取首页BookInfo和ItemInfo并进行页面跳转
     * 修改日期：2019.10.21
     */
    public void transmitTextInfo(ItemInfo itemInfo){
        Intent intent = new Intent(View_FirstPage.this, View_EditText.class);
        intent.putExtra("ItemInfo",itemInfo);//传递Book类和Item类
        intent.putExtra("BookInfo",firstBookInfo);
        intent.putExtra("Mark",true);
        startActivity(intent);
    }
    /**
     *功能：获取首页BookInfo和ItemInfo并进行页面跳转
     * 修改日期：2019.10.21
     */
    public void transmitImageInfo(ItemInfo itemInfo){
        Intent intent = new Intent(View_FirstPage.this, View_ImgDisplay.class);
        intent.putExtra("ItemInfo",itemInfo);//传递Book类和Item类
        intent.putExtra("BookInfo",firstBookInfo);
        startActivity(intent);
    }

}